package com.example.soscall.utils;

import static com.example.soscall.Constans.TIANQI_API_PUBLIC_KEY;
import static com.example.soscall.Constans.TIANQI_API_SECRET_KEY;

import android.util.Base64;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SeniverseUtils {
    private static  SeniverseUtils seniverseUtils;
    private SeniverseUtils(){}
    public static SeniverseUtils getInstance(){
        if(seniverseUtils == null){
            seniverseUtils = new SeniverseUtils();
        }
        return seniverseUtils;
    }
    private final Map<String, String> paramMap = new HashMap<>();
    public static final String WEATHERURL = "https://api.seniverse.com/v3/weather/now.json";

    private void addParameter(String key, String value) {
        this.paramMap.put(key, value);
    }

    private void addParameter(String key, long value) {
        this.paramMap.put(key, String.valueOf(value));
    }

    public void removeParameter(String key) {
        this.paramMap.remove(key);
    }

    public String getUrl(String location) throws NoSuchAlgorithmException, InvalidKeyException {
        this.paramMap.clear();
        addParameter("ts", new Date().getTime() / 1000);
        addParameter("fields", "precip_minutely");
        addParameter("ttl", "1800");
        addParameter("public_key", TIANQI_API_PUBLIC_KEY);
        addParameter("location",location);
        Set<String> paramSet = this.paramMap.keySet();
        String secretKey = TIANQI_API_SECRET_KEY;
        List<String> paramList = new ArrayList<>(paramSet);

        paramList.sort(Comparator.naturalOrder());
        boolean isFirst = true;
        StringBuilder stringBuilder = new StringBuilder();

        for (String key : paramList) {
            if (isFirst) {
                isFirst = false;
            } else {
                stringBuilder.append("&");
            }
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(this.paramMap.get(key));
        }

        String query = stringBuilder.toString();

        Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));

        String sig = null;
//       sig = Base64.getEncoder().encodeToString(hmac.doFinal(query.getBytes(StandardCharsets.UTF_8)));
        sig = android.util.Base64.encodeToString(hmac.doFinal(query.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP);

        stringBuilder.append("&sig=");
        stringBuilder.append(sig);

        return WEATHERURL.concat("?").concat(stringBuilder.toString());
    }
}
